package org.sagitta.httprpc.json.adaptor;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

import net.sf.json.JSONObject;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.sagitta.httprpc.RequestUnmarshaller;
import org.sagitta.httprpc.exception.RPCException;
import org.sagitta.httprpc.pox.adaptor.POXUtil;
import org.sagitta.httprpc.utils.CommonUtil;

public class JSONRequestUnmashaller implements RequestUnmarshaller {

	private static final Log log = LogFactory.getLog(JSONRequestUnmashaller.class);

	@SuppressWarnings("unchecked")
	@Override
	public <T> T unmashal(Class<T> requestClass, InputStream data) throws RPCException {
		try {
			String json = getRequestText(data);
			if (log.isDebugEnabled()) {
				log.debug("Post message: " + json);
			}
			JSONObject jo = JSONObject.fromObject(json);
			if (jo.has("request")) {
				Object obj = jo.get("request");
				if (requestClass.equals(obj.getClass())) {
					return (T) obj;
				} else if (obj instanceof String && CommonUtil.isNullString(obj.toString())) {
					return null;
				} else {
					throw new RPCException(RPCException.REQUESTMASHLLERROR);
				}
			} else {
				return null;
			}
		} catch (IOException e) {
			e.printStackTrace();
			throw new RPCException(RPCException.REQUESTMASHLLERROR);
		}
	}

	private String getRequestText(InputStream is) throws IOException {
		BufferedReader reader = new BufferedReader(new InputStreamReader(is));
		StringBuilder sb = new StringBuilder();
		String s = reader.readLine();
		while (s != null) {
			sb.append(s);
			s = reader.readLine();
		}
		return POXUtil.consumeBOM(sb.toString());
	}

}
